package senders;
import java.awt.Shape;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.jhotdraw.draw.Figure;

import sr.logger.Logger;
import util.FigureWrapper;
import client.remote.ClientReceiver;

public class FigureBroadCaster extends Thread
{
	Logger logger = Logger.getLogger(this.getClass());
	private IBroadcaster masterBroadCaster;
	private BlockingQueue<Shape> messageQueue = new LinkedBlockingQueue();
	private boolean shutdown = false;
	public FigureBroadCaster(IBroadcaster bc)
	{
		masterBroadCaster = bc;
		start();
	}
	public void addFigure(Shape shape)
	{
		try {
			messageQueue.put(shape);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void shutdown()
	{
		shutdown = true;
	}
	@Override
	public void run()
	{
		while(!shutdown)
		{
			Shape  msg = null;
			try {
				msg = messageQueue.poll(1, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(msg != null)
			{
				logger.log("run","broadcasting main chat msg");
				ArrayList<ClientReceiver> clients = new ArrayList<ClientReceiver>(masterBroadCaster.getClients());
				Long tick = logger.log("run","addFigure");
				for(ClientReceiver client : clients)
				{
					try 
					{
						client.addFigure(msg,tick);
					} 
					catch (RemoteException e) 
					{
						masterBroadCaster.reportError(client);
						e.printStackTrace();
					}
				}
			}
		}
	}
}
